package org.intellij.doctree.actions;

import com.intellij.openapi.actionSystem.AnActionEvent;
import org.intellij.doctree.*;
import org.intellij.doctree.node.*;

public class EditNode extends TreeEditAction {

    public void actionPerformed(AnActionEvent e) {
        DocTreeComponent component = getComponent(e);
        if (component == null) return;

        DocTree tree = getTree(e);
        if (tree == null) return;

        DocTreeNode oldNode = tree.getCurrentNode();

        if (oldNode == null || !oldNode.isEditable()) return;

        NodeDialog dialog;

        if (oldNode instanceof DocumentNode) {
            dialog = new DocumentDialog(getTree(e), (DocumentNode) oldNode);
        } else if (oldNode instanceof FolderNode) {
            dialog = new FolderDialog(getTree(e), (FolderNode) oldNode);
        } else return;
        dialog.centerRelativeToParent();
        dialog.show();

        if (dialog.isOkFlag()) {
            Object newValue = dialog.getValue();
            if (oldNode instanceof DocumentNode)
                component.updateNode((DocumentNode) oldNode, (Document) newValue);
            else
                component.updateNode((FolderNode) oldNode, (Folder) newValue);
        }

    }

    public void update(AnActionEvent e) {
        boolean actionEnabled = false;
        DocTree tree = getTree(e);
        if (tree != null) {
            DocTreeNode node = tree.getCurrentNode();
            if (node != null && node.isEditable()) actionEnabled = true;
        }
        e.getPresentation().setEnabled(actionEnabled);
    }

}
